package com.hnair.bot.controller.sys;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hnair.bot.base.BaseController;
import com.hnair.bot.common.SysContants;
import com.hnair.bot.common.result.BaseResult;
import com.hnair.bot.common.result.ErrorCode;
import com.hnair.bot.common.utils.MD5Util;
import com.hnair.bot.model.BfUser;
import com.hnair.bot.model.PageInfo;
import com.hnair.bot.service.IBfUserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;


/**
 * 菜单Controller
 * 
 * @author zhulei
 *
 */
@Controller
@SuppressWarnings("all")
public class UserController extends BaseController{		
	private final static Logger log = LoggerFactory.getLogger(UserController.class);
	@Autowired
	private IBfUserService userService;
	
	@RequestMapping("/user/index")
	public String index(HttpServletRequest request) {
		return "pages/user/index";
	}
	
	@RequestMapping("/user/add")
	public String add(HttpServletRequest request) {
		return "pages/user/add";
	}
	

	@RequestMapping("/user/edit")
	public ModelAndView edit(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("pages/user/edit");
		modelAndView.addObject("id", request.getParameter("id"));
		return modelAndView;
	}
	
	@RequestMapping("/user/detail")
	public ModelAndView detail(HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("pages/user/detail");
		modelAndView.addObject("id", request.getParameter("id"));
		return modelAndView;
	}
	
	@RequestMapping("/user/editPasswd")
	public ModelAndView editPwd(HttpServletRequest request) {
		
		Subject currentUser = SecurityUtils.getSubject();
		String username = (String) currentUser.getPrincipal();
		
		
		Wrapper<BfUser> wrapper=new EntityWrapper<BfUser>();
		wrapper.eq("username", username);
		
		List<BfUser> userList = userService.selectList(wrapper);
		BfUser user = userList.get(0);
		ModelAndView modelAndView = new ModelAndView("pages/user/editPasswd");
		modelAndView.addObject("id",user.getId().toString());
		return modelAndView;
	}

	/**
	 * 用户管理
	 * 
	 * @param
	 * @return
	 * @throws
	 */
	@RequestMapping(value = { "/rest/userList" }, method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> userList(HttpServletRequest request,BfUser user,PageInfo pageInfo) {

		  
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			BfUser userSession=(BfUser)request.getSession().getAttribute("userInfo");
			log.info("获取用户session值：" + userSession.toString());
//			user.setOrgIdList(userSession.getOrgIdList());
//			user.setPaginationInfo(paginationInfo);
//			List<ParkUser> userList = userService.selectByExample(user);
//			
//			res.put("total", user.getPaginationInfo().getTotalRecord());
//			//res.put("total", paginationInfo.getTotalRecord());
//			res.put("rows", userList);
			
			Wrapper<BfUser> wrapper=new EntityWrapper<BfUser>();
    		//添加条件查询
			if(StringUtils.isNotEmpty(user.getAdminPhone())){
				wrapper.eq("admin_phone", user.getAdminPhone());
			}
			/*if(userSession.getBfCompany().getCompanyType()!= SysContants.COMPANY_TYPE_0){
				wrapper.eq("company_id", userSession.getCompanyId());
			}*/
       	
//        	//单位id
//        	if(user.getCompanyId() != null){
//        		wrapper.eq("company_id", user.getCompanyId());
//        	}
			
    		Page<BfUser> page=new Page<BfUser>(pageInfo.getPage(),pageInfo.getRows());
    		Page<BfUser> dictList = userService.selectPage(page, wrapper);
    		res.put("rows", dictList.getRecords());
			res.put("total", dictList.getTotal());	
			res.put("success", "true");
			return res;
		} catch (Exception e) {
			res.put("success", "false");
			return res;
		} 	
		
	}
	
	/**
	 * 用户管理
	 * 添加用户
	 * @param
	 * @return
	 * @throws
	 */
	@RequestMapping(value = { "/rest/userAdd" }, method = RequestMethod.POST)
	public @ResponseBody
	BaseResult userAdd(HttpServletRequest request,@Valid BfUser user,BindingResult result) {
	   
		BfUser BfUser = (BfUser) request.getSession().getAttribute("userInfo");
		
		BaseResult serviceResult = new BaseResult(ErrorCode.SuccessRetCode, ErrorCode.SuccessRetInfo, null);
		
		if (result.hasErrors()){
            List<ObjectError> errorList = result.getAllErrors();
            for(ObjectError error : errorList){
                System.out.println(error.getDefaultMessage());
            }
			return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo+result.toString());
        }
		try {		

			user.setStatus(new Integer(1));
			user.setCreateTime(new Date());
			user.setCreator(BfUser.getAdminName());
			
			//管理员手机号
			if(StringUtils.isNotBlank(user.getAdminPhone())){
				Wrapper<BfUser> wrapper=new EntityWrapper<BfUser>();
	        	wrapper.eq("userName", user.getAdminPhone());
	        	List<BfUser> comList = userService.selectList(wrapper);
	        	if(comList != null && comList.size()>0){
	        		serviceResult.setRetCode(ErrorCode.VerifyErrorRetCode);
	        		serviceResult.setRetMsg("管理员手机号重复");
	        		return serviceResult;
	        	}else{
	        		user.setUsername(user.getAdminPhone());
	        	}
			}
			
			
			//管理员身份证校验
			if(StringUtils.isNotBlank(user.getIdentificationCard())){
				Wrapper<BfUser> wrapper=new EntityWrapper<BfUser>();
	        	wrapper.eq("identification_card", user.getIdentificationCard());
	        	List<BfUser> comList = userService.selectList(wrapper);
	        	if(comList != null && comList.size()>0){
	        		serviceResult.setRetCode(ErrorCode.VerifyErrorRetCode);
	        		serviceResult.setRetMsg("管理员身份证号重复");
	        		return serviceResult;
	        	}
			}
			
			userService.insert(user);
			this.saveUserlog(request, "用户管理："+ user.getUsername() +"进行添加操作");
			
			return BaseResult.success();
		} catch (Exception e) {
			return BaseResult.exception(e.getMessage());
		}
		
	}
	
	/**
	 * 用户管理
	 * 获取用户详情
	 * @param
	 * @return
	 * @throws
	 */
	@RequestMapping(value = { "/rest/userInfo" }, method = RequestMethod.GET)
	public @ResponseBody
	BaseResult userInfo(HttpServletRequest request) {
		
		BfUser user=null;
		try {	
			Long id=Long.parseLong( request.getParameter("id"));
			user=userService.selectById(id);
			return BaseResult.success(user);
		} catch (Exception e) {
			return BaseResult.exception(e.getMessage());
		}
		
	}
	
	/**
	 * 用户管理
	 * 更新用户
	 * @param
	 * @return
	 * @throws
	 */
	@RequestMapping(value = { "/rest/userUpdate" }, method = RequestMethod.POST)
	public @ResponseBody
	BaseResult userUpdate(HttpServletRequest request,@Valid BfUser user,BindingResult result) {
		BfUser BfUser = (BfUser) request.getSession().getAttribute("userInfo");

		if (result.hasErrors()){
            List<ObjectError> errorList = result.getAllErrors();
            for(ObjectError error : errorList){
                System.out.println(error.getDefaultMessage());
            }
			return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode, ErrorCode.ParaCheckErrorRetInfo+result.toString());
        }
		try {
			
			user.setUpdator(BfUser.getAdminName());
			user.setUpdateTime(new Date());
			userService.updateById(user);
			
			this.saveUserlog(request, "用户管理："+user.getUsername()+"修改用户信息");
			
			return BaseResult.success();
		} catch (Exception e) {
			log.error("用户信息修改异常",e);
			return BaseResult.exception(e.getMessage());
		}
		
	}
	
	/**
	 * 密码检查
	 * @param request
	 * @param user
	 * @param result
	 * @return
	 */
	@RequestMapping(value = { "/rest/checkuser" }, method = RequestMethod.POST)
	public @ResponseBody
	BaseResult useCheck(HttpServletRequest request) {
		
		BfUser user=null;
		
	    user=(BfUser)request.getSession().getAttribute("userInfo");
		
		try {	
			Long id=Long.parseLong(request.getParameter("id"));
			
			user=userService.selectById(id);
			
			this.saveUserlog(request, user.getUsername()+":修改密码操作");
			
			boolean flag = MD5Util.checkPassword(request.getParameter("userpasswd"),user.getUserpasswd());
			if(flag){
				return BaseResult.success(user);
			}
			return BaseResult.exception("原始密码输入错误");
			
		} catch (Exception e) {
			return BaseResult.exception(e.getMessage());
		}
		
	}
	
	
	/**
	 * restful
	 * 删除用户
	 * @param req
	 * @return

	 */
	@RequestMapping(value = { "/rest/userDel" }, method = RequestMethod.POST)
	public @ResponseBody
	BaseResult userDel(HttpServletRequest request,String ids){
		BfUser user=(BfUser)request.getSession().getAttribute("userInfo");
		try {
			userService.deleteBatchIds(Arrays.asList(ids.split(",")));
			this.saveUserlog(request, "用户管理："+user.getUsername()+"删除操作");
			return BaseResult.success();
		} catch (Exception e) {
			return BaseResult.exception(e.getMessage());
		}
	}
}
